package cn.tedu.egmvc3.base.exception;

import cn.tedu.egmvc3.base.response.JsonResult;
import cn.tedu.egmvc3.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        String date = ex.getMessage();
        log.error("IllegalArgumentException={}",date);
        return new JsonResult(StatusCode.OPERATION_FAILED,date);
    }
    @ExceptionHandler
    public JsonResult doHandleBindException(BindException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("BindException={}",data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("doHandleConstraintViolationException:{}", data);
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }
   /* @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        String data = ex.getMessage();
        log.error("RuntimeException={}",data);
        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable ex){
        String data = ex.getMessage();
        log.error("Throwable={}",data);
        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
    }*/

}
